<?php
declare (strict_types = 1);

namespace app\controller;

use app\BaseController;
use app\common\Pay;
use app\common\UserService;
use app\job\Task;
use app\model\Category;
use app\model\Super;
use app\model\SuperOrders;
use app\model\SuperOrdersAfter;
use app\model\SuperOrdersAssess;
use app\model\SuperOrdersDetail;
use app\model\SuperShopcar;
use app\model\SuperSpec;
use app\model\User;
use app\tool\Random;
use think\db\Query;
use think\facade\Db;
use think\facade\Queue;

class SuperController extends BaseController
{
	/**
	 * 类目
	 * @return void
	 */
	function class()
	{
		$rows = Category::where(['type'=>'super','pid'=>0])->order(['weigh' => 'desc'])->select();
		$this->writeJson($rows);
	}
	
	/**
	 * 列表
	 * @return void
	 */
	function index()
	{
		$first_class_id = $this->request->get('first_class_id/d');
		$price = $this->request->get('price');
		$sales = $this->request->get('sales');
		$keyword = $this->request->get('keyword');
		$rows = Super::withMin(['spec' => 'min_price'], 'price')
			->when(!empty($first_class_id), function (Query $query) use ($first_class_id) {
				$query->where('class_id',$first_class_id);
			})->when(!empty($price), function (Query $query) use ($price) {
				$query->order(['min_price' => $price]);
			})->when(!empty($sell), function (Query $query) use ($sales) {
				$query->order(['sales' => $sales]);
			})->when(!empty($keyword), function (Query $query) use ($keyword) {
				$query->whereLike('name', '%' . $keyword . '%');
			})
			->order(['id'=>'desc'])
			->paginate()
			->items();
		$this->writeJson($rows);
	}
	
	/**
	 * 详情
	 * @return void
	 */
	function detail()
	{
		$super_id = $this->request->get('super_id/d');
		$row = Super::withMin(['spec' => 'min_price'], 'price')
			->with(['spec','user_collect'=>function (Query $query) {
				$query->where('user_id', $this->user_id);
			}])
			->filter(function ($data)use($super_id){
				$data->shopcar_count = SuperShopcar::where(['user_id'=>$this->user_id,'super_id'=>$super_id])->count();
			})
			->findOrFail($super_id);
		$this->writeJson($row);
	}
	
	function collect()
	{
		$super_id = $this->request->post('super_id/d');
		$ret = UserService::collect($super_id, $this->user_id,2);
		$this->writeJson($ret);
	}
	
	
	/**
	 * 创建订单
	 * @return void
	 */
	function createOrder()
	{
		$super_id = $this->request->post('super_id/d'); //商品
		$spec_id = $this->request->post('spec_id/d');
		$num = $this->request->post('num/d', 1); //数量
		$address_id = $this->request->post('address_id/d');
		$mark = $this->request->post('mark','');
		$spec = SuperSpec::findOrFail($spec_id);

		if (empty($address_id)) {
			$this->writeJson(0, '请选择收货地址');
		}
		if ($spec->sku < $num) {
			$this->writeJson(0, '商品库存不足');
		}
		
		//修改库存
		$spec->sku -= $num;
		$spec->save();
		$pay_amount = $spec->price * $num;
		$ordersn = Random::ordersn();
		
		
		$data = [
			'address_id' => $address_id,
			'user_id' => $this->user_id,
			'order_sn' => $ordersn,
			'pay_amount' => $pay_amount,
			'mark'=>$mark
		];
		
		// 启动事务
		Db::startTrans();
		try {
			$order = SuperOrders::create($data);
			$order->detail()->save([
				'super_id' => $super_id,
				'spec_id' => $spec_id,
				'amount' => $spec->price,
				'num' => $num,
			]);
			// 提交事务
			Db::commit();
		} catch (\Exception $e) {
			// 回滚事务
			Db::rollback();
			$this->writeJson(0, $e->getMessage());
		}
		Queue::later(60*15, Task::class, ['order_id' => $order->id, 'action' => 'super_order_timeout'], 'task');
		$this->writeJson($order);
	}
	
	
	function orderPay()
	{
		$order_id = $this->request->post('order_id/d');
		$pay_type = $this->request->post('pay_type/d');
		$row = SuperOrders::where(['user_id' => $this->user_id, 'status' => 1])->findOrFail($order_id);
		$user = User::findOrFail($this->user_id);
		// 启动事务
		Db::startTrans();
		try {

			if (in_array($pay_type, [1, 2])) {
				$ret = Pay::pay($pay_type, $row->pay_amount, $row->order_sn, '购买商品', 'super', $user->openid);
			} else {
				UserService::changeUserMoney(-$row->pay_amount, $user->id, '购买商品');
				app(NotifyController::class)->returnNotify(request()->setRoute(['paytype' => 'balance', 'out_trade_no' =>  $row->order_sn, 'attach' => 'super']));
				$ret = true;
			}
            $row->pay_source = request()->header('Client');
			$row->pay_type = $pay_type;
			$row->save();
			// 提交事务
			Db::commit();
		} catch (\Exception $e) {
			// 回滚事务
			Db::rollback();
			$this->writeJson(0, $e->getMessage());
		}
		$this->writeJson($ret);
	}
	
	/**
	 * 价格计算
	 * @return void
	 */
	function getPrice()
	{
		$spec_id = $this->request->get('spec_id/d');
		$num = $this->request->get('num/d');
		$spec = SuperSpec::findOrFail($spec_id);
		if ($spec->sku < $num) {
			$this->writeJson(0, '商品库存不足');
		}
		
		$pay_amount = $spec->price * $num;
		$this->writeJson(['pay_amount' => $pay_amount]);
	}
	
	/**
	 * 加入购物车
	 * @return void
	 */
	function shopcarAdd()
	{
		$super_id = $this->request->post('super_id/d');
		$spec_id = $this->request->post('spec_id/d');
		$num = $this->request->post('num/d', 1);
		
		$car = SuperShopcar::where(['user_id' => $this->user_id, 'super_id' => $super_id, 'spec_id' => $spec_id])->find();
		if ($car) {
			$car->num += $num;
			$car->save();
		} else {
			SuperShopcar::create([
				'user_id' => $this->user_id,
				'super_id' => $super_id,
				'spec_id' => $spec_id,
				'num' => $num,
			]);
		}
		$this->writeJson('加入成功');
	}
	
	/**
	 * 购物车列表
	 * @return void
	 */
	function shopcarList()
	{
		$rows = SuperShopcar::where(['user_id' => $this->user_id])
			->with(['super', 'spec'])
			->paginate()
			->items();
		$this->writeJson($rows);
	}
	
	/**
	 * 修改购物车
	 * @return void
	 */
	function shopcarEdit()
	{
		$shopcar_id = $this->request->post('shopcar_id/d');
		$num = $this->request->post('num/d', 1);
		$spec_id = $this->request->post('spec_id/d', 0);
		$row = SuperShopcar::findOrFail($shopcar_id);
		if (!empty($num)) {
			$row->num = $num;
		}
		if (!empty($spec_id)) {
			$row->spec_id = $spec_id;
		}
		$row->save();
		$this->writeJson();
	}
	
	/**
	 * 删除购物车
	 * @return void
	 */
	function shopcarDelete()
	{
		$shopcar_id = $this->request->post('shopcar_id');
		$row = SuperShopcar::where('id',$shopcar_id)->selectOrFail();
		$row->delete();
		$this->writeJson();
	}
	
	/**
	 * 购物车支付
	 * @return void
	 */
	function shopcarCreateOrder()
	{
		$shopcar_id = $this->request->post('shopcar_id');
		$pay_type = $this->request->post('pay_type/d');
		$address_id = $this->request->post('address_id/d', 0);
		$row = SuperShopcar::where('id', $shopcar_id)->findOrFail();
		$user = User::findOrFail($this->user_id);
		if (empty($address_id)) {
			$this->writeJson(0, '请选择收货地址');
		}
		$pay_amount = 0;
		$detail = [];
		if ($row->spec->sku < $row->num) {
			$this->writeJson(0, '商品库存不足');
		}
		//修改库存
		$row->spec->sku -= $row->num;
		$row->together(['spec'])->save();
		$pay_amount += $row->spec->price * $row->num;
		$detail[] = [
			'super_id' => $row->super_id,
			'spec_id' => $row->spec_id,
			'amount' => $row->spec->price,
			'num' => $row->num,
		];
		$ordersn = Random::ordersn();
		// 启动事务
		Db::startTrans();
		try {
			$order = SuperOrders::create([
				'address_id' => $address_id,
				'user_id' => $this->user_id,
				'pay_amount' => $pay_amount,
				'order_sn' => $ordersn,
				'pay_type'=>$pay_type
			]);
			
			$order->detail()->saveAll($detail);
			
			if (in_array($pay_type, [1, 2])) {
				$ret = Pay::pay($pay_type, $pay_amount, $ordersn, '购买商品', 'super', $user->openid);
			} else {
				UserService::changeUserMoney(-$pay_amount, $user->id, '购买商品');
				app(NotifyController::class)->returnNotify(request()->setRoute(['paytype' => 'balance', 'out_trade_no' =>  $ordersn, 'attach' => 'super']));
				$ret = true;
			}
			// 提交事务
			Db::commit();
		} catch (\Exception $e) {
			// 回滚事务
			Db::rollback();
			$this->writeJson(0, $e->getMessage());
		}
		//删除购物车
		$rows = SuperShopcar::where('id', $shopcar_id)->findOrFail(); //*****重新查询删除
		$rows->delete();
		
		Queue::later(60*15, Task::class, ['order_id' => $order->id, 'action' => 'goods_order_timeout'], 'goods');
		$this->writeJson($ret);
	}
	
	
	/**
	 * 购物车价格计算
	 * @return void
	 */
	function shopcarGetPrice()
	{
		$shopcar_id = $this->request->get('shopcar_id');
		
		$row = SuperShopcar::where('id', $shopcar_id)->findOrFail();
		$pay_amount = 0;
		if ($row->spec->sku < $row->num) {
			$this->writeJson(0, '商品库存不足');
		}
		$pay_amount += $row->spec->price * $row->num;
		$this->writeJson(['pay_amount' => $pay_amount]);
	}
	
	
	/**
	 * 订单列表
	 * @return void
	 */
	function orderList()
	{
		$status = $this->request->get('status/d'); // 0全部 1待付款 2待发货 3待收货 4已完成 5售后/退款
		$rows = SuperOrders::where(['user_id' => $this->user_id])
			->with(['detail' => function (Query $query) {
				$query->with(['super', 'spec']);
			},'after'=>function (Query $query) {
				$query->with(['orders_detail'=>function (Query $query) {
					$query->with(['super']);
				}]);
			}])
			->when(!empty($status), function (Query $query) use ($status) {
				switch ($status) {
					case 1:
						$query->where(['status' => 1]);
						break;
					case 2:
						$query->where(['status' => 2]);
						break;
					case 3:
						$query->where(['status' => 3]);
						break;
					case 4:
						$query->whereIn('status', [4,5]);
						break;
					case 5:
						$query->whereIn('status', [7,8,9,10,11,12]);
						break;
				}
			})
			->order(['id' => 'desc'])
			->paginate()
			->items();
		$this->writeJson($rows);
	}
	
	#订单详情
	function orderDetail()
	{
		$order_id = $this->request->get('order_id/d');
		$row = SuperOrders::where(['user_id' => $this->user_id, 'id' => $order_id])
			->with(['detail' => function (Query $query) {
				$query->with(['super', 'spec']);
			}, 'address'])
			->findOrFail();
		$this->writeJson($row);
	}
	
	
	#取消订单
	function orderCancel()
	{
		$order_id = $this->request->post('order_id/d');
		$row = SuperOrders::where(['user_id' => $this->user_id, 'id' => $order_id, 'status' => 1])->findOrFail();
		$row->status = 6;
		$row->save();
		$this->writeJson();
	}
	
	/**
	 * 订单删除
	 * @return void
	 */
	function orderDelete()
	{
		$order_id = $this->request->post('order_id/d');
		$row = SuperOrders::where(['user_id' => $this->user_id, 'id' => $order_id])->whereIn('status',[5,6])->findOrFail();
		$row->delete();
		$this->writeJson();
	}
	
	#订单详情列表
	function orderDetailList()
	{
		$order_id = $this->request->get('order_id/d');
		$rows = SuperOrdersDetail::where(['order_id' => $order_id])
			->with(['super','spec'])
			->select();
		$this->writeJson($rows);
	}
	
	function getAssessList()
	{
		$super_id = $this->request->get('super_id/d');
		$type = $this->request->get('type/d');
		$rows = SuperOrdersAssess::where(['super_id' => $super_id])
			->with(['user'])
			->when(!empty($type), function (Query $query) use ($type) {
				if ($type == 1) {
					$query->where('score', 5);
				}
				if ($type == 2) {
					$query->whereBetween('score', [2, 4]);
				}
				if ($type == 3) {
					$query->where('score', 1);
				}
				if ($type == 4) {
					$query->where('images', '<>', '');
				}
			})
			->order(['id' => 'desc'])
			->paginate()
			->items();
		foreach ($rows as $row){
			if ($row->anonymous == 1){
				$row->user->nickname = '匿名';
			}
		}
		$assess_count = SuperOrdersAssess::where(['super_id' => $super_id])->count();//总数
		$good_count = SuperOrdersAssess::where(['super_id' => $super_id])->where('score', 5)->count();//好评
		$just_count = SuperOrdersAssess::where(['super_id' => $super_id])->whereBetween('score', [2, 4])->count();//中评
		$bad_count = SuperOrdersAssess::where(['super_id' => $super_id])->where('score', 1)->count();//差评
		$images_count = SuperOrdersAssess::where(['super_id' => $super_id])->where('images', '<>', '')->count();//有图
		$this->writeJson(['count' => $assess_count, 'good_count' => $good_count, 'just_count' => $just_count, 'bad_count' => $bad_count, 'images_count' => $images_count, 'list' => $rows]);
	}
	
	#售后
	function orderAfter()
	{
		$order_id = $this->request->post('order_id/d');
		$type = $this->request->post('type/d');
		$state = $this->request->post('state/d');
		$apply_reason = $this->request->post('apply_reason');
		$refund_amount = $this->request->post('refund_amount');
		$content = $this->request->post('content');
		$images = $this->request->post('images');
		$mobile = $this->request->post('mobile');
		$order = SuperOrders::where([ 'id' => $order_id])->findOrFail();
		if (!in_array($order->status,[2,3])){
			$this->writeJson(0, '订单状态异常');
		}
		if ($refund_amount > $order->pay_amount){
			$this->writeJson(0, '退款金额不能大于支付金额');
		}

		SuperOrdersAfter::create([
			'order_id' =>  $order->id,
			'user_id' => $this->user_id,
			'type' => $type,
			'state' => $state,
			'apply_reason' => $apply_reason,
			'refund_amount' => $refund_amount,
			'content' => $content,
			'images' => $images,
			'mobile' => $mobile,
		]);
		$order->status = 7;
		$order->save();
		$this->writeJson();
	}
	
	#撤销售后
	function orderCancelAfter()
	{
		$order_id = $this->request->post('order_id/d');
		$row = SuperOrders::where(['user_id' => $this->user_id, 'id' => $order_id])->whereIn('status',[7,8])->findOrFail();
		$row->status = 12;
		$row->save();
		$this->writeJson();
	}
	
	#售后退货
	function orderAfterReturn()
	{
		$order_id = $this->request->post('order_id/d');
		$return_waybill = $this->request->post('return_waybill');
		$return_express = $this->request->post('return_express');
		$order = SuperOrders::where(['id' => $order_id])->findOrFail();
		if ($order->status != 8){
			$this->writeJson(0,'订单状态异常');
		}
		$order->return_waybill = $return_waybill;
		$order->return_express = $return_express;
		$order->status = 9;
		$order->returntime = time();
		$order->save();
		$this->writeJson();
	}
	
	#确认收货
	function orderConfirm()
	{
		$order_id = $this->request->post('order_id/d');
		$row = SuperOrders::where(['user_id' => $this->user_id, 'id' => $order_id])->whereIn('status',[3,11,12])->findOrFail();
		$row->status = 4;
		$row->confirmtime = time();
		$row->save();
		$this->writeJson();
	}
	
	function orderAssess()
	{
		$anonymity = $this->request->post('anonymity/d'); #匿名:1=是,2=否
		$order_id = $this->request->post('order_id/d');
		$assess = $this->request->post('assess/a');#评价内容 [{"order_detail_id":"xx“,"super_id":"xxx","score":"xxx","images":"xxxx","content":"xx"}]
		if (empty($assess)||empty($anonymity)){
			$this->writeJson(0,'参数错误');
		}
		$order = SuperOrders::where(['user_id' => $this->user_id, 'id' => $order_id, 'status' => 4])->findOrFail();
		foreach ($assess as $item){
			$item['user_id'] = $this->user_id;
			SuperOrdersAssess::create($item);
		}
		$order->status = 5;
		$order->save();
		$this->writeJson();
	}
	
	
	
	

	
	
	

	
}
